<template>
	<block v-if="isopen">
		<view class="payment">
			<view class="pay-info">
				<view class="merchant">
					<image class="merchant-image" :src="shopInfo.store_banner" mode="scaleToFill"></image>
					<view>
						<view class="merchant-name">{{shopInfo.store_name}}</view>
						<view class="merchant-address">
							{{shopInfo.city_name + shopInfo.district_name + shopInfo.address}}</view>
					</view>
				</view>
				<view class="amount">
					<view class="amount-title">金额（元)</view>
					<view class="amount-value">
						&yen;
						<input class="amount-input" placeholder-class="pay-input-placeholder" placeholder="请输入消费金额"
							type="digit" v-model="money" />
					</view>
					<block v-if="memberInfo.member_id">
						<view v-if="memberInfo.member_id && money > 0" class="amount-tip">买单成功，可获得积分约：{{rebateConsume}}
						</view>
					</block>
					<block v-else>
						<view class="pay-tips">登录用户，可额外获得积分奖励</view>
					</block>
				</view>
			</view>
			<view class="allotment">
				<!-- <view class="allot-item">
					<view class="allot-main">
						<view class="allot-title">贡献积分(共{{memberInfo.point}})</view>
						<block v-if="memberInfo.point > 0 && shopInfo.point_rate > 0">
						<input class="allot-value" placeholder-class="placeholder" type="digit" placeholder="`当前${point_money || 0},最高可抵${pointRate}`" v-model="point"/>
						</block> 
						<block v-else><view class="allot-tip">登录后可使用贡献积分</view></block>
					</view>
				</view> -->

				<view class="allot-item">
					<view class="allot-main">
						<view class="allot-title">账户消费券</view>
						<block v-if="memberInfo.balance_money > 0">
							<input class="allot-value" placeholder-class="placeholder" type="digit"
								:placeholder="memberInfo.balance_money + ' 可用'" v-model="balance_money" />
						</block>
						<block v-else>
							<view class="allot-tip">登录账号可使用消费券</view>
						</block>
					</view>
					<view v-if="!memberInfo.member_id">
						<view class="bind-box">
							<view class="bind-button" @click="toBind">登录领取消费券</view>
						</view>
					</view>
				</view>

			</view>
			<view class="actual-pay">
				<view class="actual-title">实际支付</view>
				<view class="actual-value"><text>&yen;</text>{{realMoney}}</view>
			</view>
			<button class="payment-button" :disabled="!submitable" type="default" @click="toPay">付款</button>
			<ns-login ref="login"></ns-login>
			<bind-mobile ref="bindMobile"></bind-mobile>
			<loading-cover ref="loadingCover"></loading-cover>
		</view>
	</block>
	<block v-else>
		<text
			style="display: flex;height: 100vh;width:100%;align-items: center;justify-content: center;font-size: 60rpx;color: #ccc;">功能暂停使用</text>
	</block>
</template>

<script>
	import {
		Weixin
	} from 'common/js/wx-jssdk.js';
	import bindMobile from '@/components/bind-mobile/bind-mobile.vue';
	export default {
		components: {
			bindMobile
		},
		data() {
			return {
				isopen: true,
				authInfo: {},
				openid: '',
				siteId: '',
				shopInfo: {},
				memberInfo: {},
				payCtrl: false,
				money: '',
				type: 1, //1微信,2支付宝
				point: '',
				account5: '',
				balance_money: '',
				point_money: '',
				debug: '',
				offline_pay_limit: 0,
				shop_online_limit: 0,
				day_user_coupon_status: true,
				day_user_coupon_max: 0,
			}
		},
		computed: {
			submitable() {
				return this.money > 0 ? true : false;
			},
			realMoney() {
				let money = this.money > 0 ? this.money : 0;
				let order_deduct = parseFloat(money - this.balance_money - this.account5 - this.point_money).toFixed(2);
				return order_deduct > 0 ? order_deduct : 0;
			},
			account5Rate() {
				let money = this.money > 0 ? this.money : 0;
				let order_deduct = parseFloat(this.shopInfo.account5_rate * money / 100)
				return (order_deduct > parseFloat(this.memberInfo.account5)) ? parseFloat(this.memberInfo.account5) :
					order_deduct;
			},
			balanceMoneyRate() {
				let money = this.money > 0 ? this.money : 0;
				let order_deduct = parseFloat(money - this.account5 - this.point_money)
				return (order_deduct > parseFloat(this.memberInfo.balance_money)) ? parseFloat(this.memberInfo
					.balance_money) : order_deduct;
			},
			pointRate() {
				let money = this.money > 0 ? this.money : 0;
				let order_deduct = parseFloat((this.shopInfo.point_rate * money) / (100 * this.memberInfo.point_value))
				return (order_deduct > parseFloat(this.memberInfo.point)) ? parseFloat(this.memberInfo.point) :
					order_deduct;
			},
			rebatePoint() {
				return parseFloat(this.shopInfo.shop_rate * this.shopInfo.user_rate * (this.realMoney - (-this
					.balance_money)) / 10000).toFixed(2);
			},
			rebateConsume() {
				return parseFloat(this.shopInfo.shop_rate * this.shopInfo.point_user_rate * (this.realMoney - (-this
					.balance_money)) / 10000).toFixed(2);
			},
			storeToken() {
				return this.$store.state.token;
			}
		},
		// 引入支付宝jsapi
		mounted() {
			if (this.$util.isAlipay()) {
				const s = document.createElement('script');
				s.type = 'text/javascript';
				s.src = 'https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.min.js';
				document.body.appendChild(s);
				window.onload = () => { //初始化产生一个全局变量 AlipayJSBridge
					this.readys()
				}
			}
		},
		watch: {
			point(val) {
				if (parseFloat(val) > 0) {
					this.point_money = parseFloat(val * this.memberInfo.point_value);
					if (this.point_money < 0.01) {
						setTimeout(() => {
							this.point = this.pointRate;
							this.point_money = parseFloat(this.pointRate * this.memberInfo.point_value).toFixed(2);
							this.$forceUpdate();
						}, 1);
					}
					if (parseFloat(val) > this.pointRate) {
						setTimeout(() => {
							this.point = this.pointRate;
							this.point_money = parseFloat(this.pointRate * this.memberInfo.point_value).toFixed(2);
							this.$forceUpdate();
						}, 1);
					} else {
						setTimeout(() => {
							this.point = parseFloat(this.point).toFixed(2);
							this.point_money = parseFloat(this.point * this.memberInfo.point_value).toFixed(2)
							this.$forceUpdate();
						}, 1);
					}
				} else {
					this.point_money = 0;
				}
			},
			account5(val) {
				if (parseFloat(val) > 0) {
					if (parseFloat(val) > parseFloat(this.memberInfo.account5)) {
						setTimeout(() => {
							this.account5 = parseFloat(this.memberInfo.account5).toFixed(2);
							this.$forceUpdate();
						}, 1);
					}
				}
			},
			balance_money(val) {
				if (parseFloat(val) > 0) {
					let order_deduct = parseFloat(this.money - this.account5 - this.point_money).toFixed(2)
					if (parseFloat(val) > order_deduct) {
						setTimeout(() => {
							this.balance_money = order_deduct;
							this.$forceUpdate();
						}, 1);
					}
					if (parseFloat(val) > parseFloat(this.memberInfo.balance_money)) {
						setTimeout(() => {
							this.balance_money = parseFloat(this.memberInfo.balance_money).toFixed(2);
							this.$forceUpdate();
						}, 1);
					}
				}
			},
			storeToken: function(nVal, oVal) {
				this.getShopInfo();
			}
		},
		methods: {
			toBind() {
				let authInfo = uni.getStorageSync('authInfo');
				if (!authInfo) authInfo = uni.getStorageSync('payAuthInfo');
				if (authInfo) {
					uni.setStorageSync('authInfo', authInfo);
					this.$refs.bindMobile.open();
				} else {
					this.$util.redirectTo('/otherpages/login/register/register');
				}
			},
			readys(callback) {
				if (window.AlipayJSBridge) { // 如果jsbridge已经注入则直接调用
					callback && callback();
				} else { // 如果没有注入则监听注入的事件
					document.addEventListener('AlipayJSBridgeReady', callback, false);
				}
			},
			//获取店铺详细信息
			getShopInfo() {
				this.$api.sendRequest({
					url: '/collection/api/collection/getShopInfo',
					data: {
						site_id: this.siteId
					},
					success: res => {
						if (res.code == 0) {
							this.shopInfo = res.data.shop;
							this.memberInfo = res.data.member;
							this.offline_pay_limit = res.data.offline_pay_limit;
							this.shop_online_limit = res.data.shop_online_limit;
							this.day_user_coupon_max = res.data.day_user_coupon_max;
							this.day_user_coupon_status = res.data.day_user_coupon_status;

							// this.isopen = res.data.h5pay_status;
						}
						uni.setNavigationBarTitle({
							title: this.shopInfo.store_name
						})
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					},
					fail: res => {
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					}
				});
			},
			// alipay(collectionNo,tradeNO) {
			// 	var _this = this;
			// 	// 通过传入交易号唤起快捷调用方式
			// 	AlipayJSBridge.call("tradePay", {
			// 		tradeNO: tradeNO
			// 	}, function (res) {
			// 		if(res.resultCode != 9000){ //支付失败
			// 			uni.showModal({ content: res.resultCode+"："+res.memo, showCancel: false });
			// 		}else{
			// 			_this.$util.redirectTo('/plugpages/collection/result', {
			// 				code: collectionNo
			// 			}, '', 'redirectTo');
			// 		}
			// 	});
			// },
			toPay() {
	
				if (this.day_user_coupon_status == false) {
					this.$util.showToast({
						title: '今日用券金额已达上限！'
					});

					return;
				} else {

					if (parseFloat(this.day_user_coupon_max) > 0 && parseFloat(this.balance_money) > parseFloat(this
							.day_user_coupon_max)) {
						const tipString = '今日剩余用券金额最高为' + this.day_user_coupon_max + '元';
						this.$util.showToast({
							title: tipString
						});
						return;
					}

				}

				if (this.shop_online_limit == 1) {

					this.$util.showToast({
						title: '今日商家收款已达上限'
					});
					return;
				}

				if (this.balance_money) {
					if (parseFloat(this.offline_pay_limit) > 0 && parseFloat(this.balance_money) + parseFloat(this
						.money) >= parseFloat(this.offline_pay_limit)) {

						this.$util.showToast({
							title: '超出单笔限额'
						});
						return;
					}
				} else {
					if (parseFloat(this.offline_pay_limit) > 0 && parseFloat(this.money) >= parseFloat(this
							.offline_pay_limit)) {

						this.$util.showToast({
							title: '超出单笔限额'
						});
						return;
					}
				}




				this.authInfo = uni.getStorageSync('payAuthInfo');
				//#ifdef MP-WEIXIN
				this.type = 1;
				this.openid = this.authInfo.weapp_openid;
				//#endif
				//#ifndef MP-WEIXIN
				if (this.$util.isWeiXin()) { //微信内
					this.type = 1;
					this.openid = this.authInfo.wx_openid;
				} else if (this.$util.isAlipay()) { //支付宝内
					this.type = 2;
					this.openid = this.authInfo.ali_openid;

					uni.showLoading({
						title: openid
					});
				}
				//#endif
				if (!this.openid || this.openid == undefined) {
					this.type = 2;
				}

				uni.showLoading({
					title: '发起支付中...'
				});

				if (!this.payCtrl) {
					this.payCtrl = true;
					this.$api.sendRequest({
						url: '/collection/api/collection/createOrder',
						data: {
							openid: this.openid,
							unionid: (this.authInfo.wx_unionid || this.authInfo.wx_unionid != undefined) ? this
								.authInfo.wx_unionid : '',
							type: this.type,
							site_id: this.siteId,
							money: this.money,
							nickname: (this.authInfo.nickName || this.authInfo.nickName != undefined) ? this
								.authInfo.nickName : '',
							headimg: (this.authInfo.avatarUrl || this.authInfo.avatarUrl != undefined) ? this
								.authInfo.avatarUrl : '',
							point: this.point,
							account5: this.account5,
							balance_money: this.balance_money,
							point_money: this.point_money,
							debug: this.debug
						},
						success: res => {
							if (res.code == 0) {
								if (res.data.type == 'deduct') {
									return setTimeout(() => {
										this.$util.redirectTo(
											'/plugpages/collection/result', {
												code: res.data.collection_no
											}, '', 'redirectTo')
									}, 2000);
								}

								if (this.type == 2) { //支付宝支付													
									if (/android/i.test(navigator.userAgent)) {
										location.href = res.data.data;
									} else {
										const jumpData = {
											action: 'jumpOut',
											jumpOutUrl: res.data.data //跳转的页面
										};
										window.parent.postMessage(JSON.stringify(jumpData), '*');
									}

									// if (window.AlipayJSBridge) {
									// 	this.alipay(res.data.collection_no,tradeNO);
									// } else {
									// 	document.addEventListener('AlipayJSBridgeReady', this.alipay(res.data.collection_no,tradeNO), false);
									// }
								} else if (this.type == 1) {
									// #ifdef H5
									if (this.$util.isWeiXin()) {
										if (uni.getSystemInfoSync().platform == 'ios') {
											var url = uni.getStorageSync('initUrl');
										} else {
											var url = location.href;
										}
										let _this = this;
										// 获取jssdk配置
										this.$api.sendRequest({
											url: '/wechat/api/wechat/jssdkconfig',
											data: {
												url: url
											},
											success: jssdkRes => {
												var wxJS = new Weixin(),
													payData = res.data;
												wxJS.init(jssdkRes.data);
												wxJS.pay({
														timeStamp: String(payData.timeStamp),
														nonceStr: payData.nonceStr,
														package: payData.package,
														signType: payData.signType,
														paySign: payData.paySign
													},
													res => {
														if (res.errMsg == 'chooseWXPay:ok') {
															_this.$util.redirectTo(
																'/plugpages/collection/result', {
																	code: res.data
																		.collection_no
																}, '', 'redirectTo');
														} else {
															_this.$util.showToast({
																title: res.errMsg
															});
														}
													}
												);
											}
										});
									}
									// #endif
									// #ifdef MP-WEIXIN
									var payData = res.data;
									wx.requestOrderPayment({
										timeStamp: payData.timeStamp,
										nonceStr: payData.nonceStr,
										package: payData.package,
										signType: payData.signType,
										paySign: payData.paySign,
										orderInfo: payData.orderInfo,
										success: res => {
											this.$util.redirectTo(
												'/plugpages/collection/result', {
													code: res.data.collection_no
												}, '', 'redirectTo')
										},
										fail: res => {
											this.flag = false;
											if (res.errMsg == 'requestPayment:fail cancel') {
												this.$util.showToast({
													title: '您已取消支付'
												});
											} else {
												uni.showModal({
													content: '支付失败,失败原因: ' + res.errMsg,
													showCancel: false
												});
											}
										}
									})
									// #endif
								}
							} else {
								this.$util.showToast({
									title: res.message
								});
							}
							this.payCtrl = false;
							uni.hideLoading();
						},
						fail: res => {
							this.payCtrl = false;
							uni.hideLoading();
						}
					})
				}
			},
			/**
			 * 授权登录
			 */
			authLogin(data) {
				//保存授权信息
				uni.setStorageSync('payAuthInfo', data);
				uni.setStorageSync('authInfo', data);
				return new Promise((resolve, reject) => {
					this.$api.sendRequest({
						url: '/api/login/auth',
						data,
						success: res => {
							if (res.code >= 0) {
								uni.setStorageSync('token', res.data.token);
								this.$store.dispatch('getCartNumber');
								this.$store.commit('setToken', res.data.token);
								resolve({});
							} else {
								uni.setStorage({
									key: 'unbound',
									data: 1,
									success: () => {}
								});
								resolve({});
							}
						}
					});
				});
			},
			topayAuth() {

				return new Promise((resolve, reject) => {
					let authInfo = uni.getStorageSync('payAuthInfo');
					this.json = this.$util.isAlipay();
					if (authInfo) {
						this.authLogin(authInfo).then(() => {
							resolve({});
						});
					} else { //无授权信息去授权
						//#ifdef MP-WEIXIN
						uni.login({
							provider: 'weixin',
							timeout: 3000,
							success: res => {
								if (res.code) {
									this.$api.sendRequest({
										url: '/weapp/api/weapp/authcodetoopenid',
										data: {
											code: res.code
										},
										success: res => {
											if (res.code >= 0) {
												let data = {};
												if (res.data.openid) data.weapp_openid =
													res.data.openid;
												if (res.data.unionid) data.wx_unionid = res
													.data.unionid;
												this.authLogin(data).then(() => {
													resolve(res);
												});
											} else {
												reject({});
											}
										}
									})
								}
							},
							fail: () => {
								reject({});
							}
						});
						//#endif
						//#ifndef MP-WEIXIN
						if (this.$util.isWeiXin()) { //微信内
							this.$util.getUrlCode(urlParams => {
								if (urlParams.code == undefined) {
									this.$api.sendRequest({
										url: '/wechat/api/wechat/authcode',
										data: {
											redirect_url: location.href
										},
										success: res => {
											if (res.code >= 0) {
												location.href = res.data;
												return
											}
										}
									});
								} else {
									this.$api.sendRequest({
										url: '/wechat/api/wechat/authcodetoopenid',
										data: {
											code: urlParams.code
										},
										success: res => {
											console.log(res)
											if (res.code >= 0) {
												let data = {};
												if (res.data.openid) data.wx_openid = res.data
													.openid;
												if (res.data.unionid) data.wx_unionid = res
													.data.unionid;
												if (res.data.userinfo) Object.assign(data, res
													.data.userinfo);
												this.authLogin(data).then(() => {
													resolve(res);
												});
											} else {
												reject({});
											}
										}
									});
								}
							});
						} else if (this.$util.isAlipay()) { //支付宝内
							this.$util.getUrlCode(urlParams => {
								if (urlParams.auth_code == undefined) {
									this.$api.sendRequest({
										url: '/alipay/api/alipay/authcode',
										data: {
											redirect_url: location.href
										},
										success: res => {
											console.log('支付宝返回', res);
											if (res.code >= 0) {
												location.href = res.data;
												return
											}
										}
									});
								} else {
									this.$api.sendRequest({
										url: '/alipay/api/alipay/authcodetoopenid',
										data: {
											code: urlParams.auth_code
										},
										success: res => {
											if (res.code >= 0) {
												alert(res)
												let data = {};
												if (res.data.openid) data.ali_openid = res.data
													.openid;
												if (res.data.userinfo) Object.assign(data, res
													.data.userinfo);
												this.authLogin(data).then(() => {
													resolve(res);
												});
											} else {
												reject({});
											}
										}
									});
								}
							});
						} else { //网页端
							resolve({});
						}
						//#endif
					}
				});
			}
		},
		onShow() {
			this.topayAuth().then(() => {
				this.getShopInfo();
			})
		},
		onLoad(options) {
			this.siteId = options.site_id;
			this.debug = options.debug || 0;
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/common/css/mixins.scss';
	$fontColor: #303133;

	@mixin fontTitle {
		font-size: 28rpx;
		color: $fontColor;
		line-height: 40rpx;
	}

	@mixin box {
		background-color: #fff;
		margin: 30rpx;
		padding: 30rpx;
		border-radius: 5rpx;
	}

	.payment {
		background-color: #f7f7f7;
	}

	.pay-info {
		background: linear-gradient(25deg, #f7f7f7 0%, #f6f4fe 90%, #f6f4fe 100%);

		.merchant {
			display: flex;
			align-items: center;
			padding: 40rpx;

			.merchant-image {
				width: 120rpx;
				height: 120rpx;
				margin-right: 30rpx;
				border-radius: 20rpx;
			}

			.merchant-name {
				font-size: 32rpx;
				color: $fontColor;
				font-weight: 700;
			}

			.merchant-address {
				font-size: 24rpx;
				color: #a6a6a6;
				display: -webkit-box;
				width: 520rpx;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
				line-height: 1.5;
			}
		}

		.amount {
			background-color: #FFFFFF;
			padding: 50rpx 40rpx;
			margin: 0 40rpx;
			border-radius: 20rpx;
			border: 4rpx solid #FFFFFF;

			.amount-title {
				@include fontTitle;
			}

			.pay-tips {
				font-size: 24rpx;
				margin-top: 20rpx;
				color: #909399
			}

			.amount-value {
				@include flex(flex-start, flex-end);
				margin-top: 30rpx;
				padding-bottom: 30rpx;
				font-size: 36rpx;
				color: #323232;
				// line-height: 50rpx;
				border-bottom: 1rpx solid #efefef;

				.amount-input {
					height: 60rpx;
					margin-left: 16rpx;
					font-size: 40rpx;
					line-height: 60rpx;
					font-weight: 700;
				}

				.pay-input-placeholder {
					font-size: 36rpx;
					color: #d8d8d8;
					font-weight: 400;

				}
			}

			.amount-tip {
				margin-top: 26rpx;
				font-size: 24rpx;
				color: #55aa00;
				line-height: 34rpx;
			}

		}
	}


	.allotment {
		@include box;
		position: relative;
		margin: 40rpx;

		.bind-box {
			position: absolute;
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #00000033;
			border-radius: 20rpx;

			.bind-button {
				padding: 0 40rpx;
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 40rpx;
				font-size: 28rpx;
				color: #ffffff;
				background-color: #1786f8db;
			}

		}

		.allot-item {
			margin-top: 22rpx;

			&:first-child {
				margin-top: 0;
			}

			.allot-main {
				@include flex(space-between);

				.allot-title {
					@include fontTitle;
				}

				.allot-value {
					height: 72rpx;
					border-radius: 4rpx;
					font-size: 28rpx;
					color: $fontColor;
					text-align: right;
					border-bottom: 1rpx solid #eee;

				}

				/deep/.placeholder {
					color: #909399;
				}
			}

			.allot-tip {
				text-align: right;
				font-size: 24rpx;
				color: #909399;
				line-height: 72rpx;
			}
		}
	}

	.actual-pay {
		@include box;
		text-align: right;
		margin: 40rpx;

		.actual-title {
			@include fontTitle;
			color: #b0b0b0;
		}

		.actual-value {
			font-size: 40rpx;
			color: #FF4544;
			line-height: 50rpx;
			margin-top: 20rpx;
			font-weight: 700;

			text {
				margin-right: 20rpx;
				font-weight: 400;
				font-size: 28rpx
			}
		}
	}

	.payment-button {
		margin: 0 auto;
		width: 630rpx;
		height: 88rpx;
		border-radius: 42px;

		background: #FF4544;
		font-size: 28rpx;
		color: #fff;
		line-height: 88rpx;

		&::after {
			display: none;
		}

		&[disabled] {
			background: #FF4544 !important;
			color: #fff !important;
			opacity: 0.3;
		}
	}
</style>